package com.cdx.spring.cglibproxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author chedx
 * @data 2021/1/11 11:33 PM
 */
public class TestCglibProxy {
    public static void main(String[] args) {
        //原始类
        final CustomerService customerService = new CustomerService();

        //增强类
        Enhancer enhancer = new Enhancer();
        enhancer.setClassLoader(TestCglibProxy.class.getClassLoader());
        enhancer.setSuperclass(CustomerService.class);

        MethodInterceptor methodInterceptor = new MethodInterceptor() {
            public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                System.out.println("-----proxy log");
                Object ret = method.invoke(customerService, args);
                return ret;
            }
        };

        enhancer.setCallback(methodInterceptor);
        CustomerService service = (CustomerService) enhancer.create();
        service.login();
        service.register();
    }
}
